$(document).ready(function(){
    socia_init();
});

function socia_init() {
    $('.leaving.act_btn, .joining').on('click', socia_action);
    $('.dropdown-menu a[data-checked]').on('click', function (e) {
        let target = $(this);

        if(!target.hasClass('disabled')) {
            let icon = target.find('i.fa');
            let val = target.attr('data-checked');
            let new_val = val !== "0" ? 0 : 1;

            target.attr('data-checked', "load").addClass('disabled');
            icon.addClass('fa-spin');

            $.ajax({
                url: '/api/v1.1/',
                type: 'POST',
                async: true,
                cache: false,
                dataType: 'json',
                processData: true,
                data: { 'csrfmiddlewaretoken': getCookie('csrftoken'),
                    'query': 'mutation($uuid: UUID, $sciigoj: [String]!)' +
                    '{aplikiSciigojn(uuid: $uuid, sciigoj: $sciigoj){status, message, sciigoj}}',
                    'variables': JSON.stringify({
                        uuid: $('.' + kom_type + '_datumoj').attr('data-' + kom_type + '_uuid'),
                        sciigoj: new_val ? ["powto"] : []
                    })
                }
            })
                .done(function (response) {
                    if(response.data.aplikiSciigojn.status) {
                        let checked = response.data.aplikiSciigojn.sciigoj
                            .indexOf(target.attr('data-sciigo')) !== -1 ? 1 : 0;
                        target.attr('data-checked', checked)
                    }
                })
                .fail(function (jqXHR, textStatus) {
                    console.log("Request failed: " + textStatus);
                    target.attr('data-checked', val);
                });
            target.removeClass('disabled');
            icon.removeClass('fa-spin');
        }

        e.stopPropagation();
    });
}

function socia_action() {
    if(typeof ago_url === "undefined" || typeof kom_type === "undefined") {
        console.log('AJAX Context not found!');
        return;
    }

    let target = $(this);
    let data = socia_data(kom_type);

    if(!data) {
        console.log('No data for AJAX');
        return;
    }

    target.unbind('click', socia_action);
    toggleBlockForm(target, 24);

    $.ajax({
        url: ago_url,
        type: 'POST',
        async: true,
        data: data,
        cache: false,
        dataType: 'json',
        processData: false,
        contentType: false
    })
        .done(function (result) {
            if(result.status === 'ok') {
                setTimeout(function(){
                    $('#tuta').text(result.tuta);
                    $('.progress-bar .progress').css('width', result.procentoj + '%');
                    $('.shadow-cov-field button, .shadow-cov-field .btn-group').toggleClass('hidden-element');
                    toggleBlockForm(target);
                    target.on('click', socia_action);
                }, 1000);
            } else {
                console.log("Bad server response: " + result.err);
                toggleBlockForm(target);
            }
        })
        .fail(function (jqXHR, textStatus) {
            toggleBlockForm(target);
            console.log("Request failed: " + textStatus);
        });
}

function socia_data(type) {
    let uuid = $('.' + type + '_datumoj').attr('data-' + type + '_uuid');

    if(uuid !== undefined) {
        out = new FormData();
        out.append(type, uuid);
        out.append('csrfmiddlewaretoken', getCookie('csrftoken'));

        return out;
    }

    return false;
}